import { requestApi } from '../../../api'
import { formatImage } from '../../../utils/formatImage'

const app = getApp()

Page({
  data: {
    winWidth: 0,
    winHeight: 0,
    spuNo: '',
    spuType: 1,

    // 两列瀑布流
    colCount: 2,

    // 瀑布流各列数组高度
    heightArr: [],
    showList: [],

    // 请求状态，限制频繁请求
    praiseRequestFlag: false,

    // 加载更多...
    page: 1,
    count: 20,
    noMore: false,
  },

  onLoad: function (options) {
    // spu类型 1 主力 2系列
    this.data.spuNo = options.spu_no
    this.data.spuType = options.spu_type

    let systemInfo = {}

    try {
      systemInfo = wx.getSystemInfoSync()
    } catch (e) {
      // Do something when catch error
    }

    this.setData({
      winWidth: systemInfo.windowWidth,
      winHeight: systemInfo.windowHeight,
    })

    this.getSpuContentList()
  },

  getSpuContentList() {
    app.request({
      url: requestApi.getSpuContentList,
      login: false,
      data: {
        spu_no: this.data.spuNo,
        spu_type: this.data.spuType,
        start: (this.data.page - 1) * this.data.count,
        count: this.data.count,
      },
    }, data => {
      const showList = data.original.data.item_list || []

      // 没有更多
      if (showList.length < this.data.count) {
        this.data.noMore = true
      }

      this.initWaterfallList(showList)

      this.setData({
        showList: this.data.showList,
      })
    }, error => {
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: error,
      })
    })
  },

  // 跳转到“show详情页”
  toShowDetail(e) {
    const feedId = e.currentTarget.dataset.feedId

    wx.navigateTo({
      url: `../detail/detail?feed_id=${feedId}`
    })
  },

  // 格式化“点赞数”
  formatLikeCount(count) {
    const units = ['k', 'w']
    const pointLength = 1
    let unit = ''
    let size = count
    
    while (size >= 1000 && (unit = units.shift())) {
      size = size / 1000
    }

    return (unit === '' ? size : size.toFixed(pointLength).replace(/\.0$/, '')) + unit
  },

  // 取消/点赞：买家秀/短图文/短视频
  praiseShow(e) {
    if (!app.toLogin()) return

    if (this.data.praiseRequestFlag) return

    this.data.praiseRequestFlag = true

    const feedId = e.currentTarget.dataset.feedId
    const list = this.data.showList
    let item = null
    let columnIndex = 0
    let itemIndex = 0

    // 遍历获取show点赞卡片、瀑布流索引
    for (let i = 0; i < list.length; i++) {
      const column = list[i]

      columnIndex = i

      for (let j = 0; j < column.length; j++) {
        if (column[j].feed_id === feedId) {
          item = column[j]
          itemIndex = j

          break
        }
      }

      if (item) break
    }

    // 当前状态 已点赞 ture，未点赞 false
    const status = item.is_favorite
    const params = {}
    let url = ''

    // 短图文、短视频 属于社区内容，其使用的点赞接口 与买家秀点赞接口 不一致
    // feed_type: feed类型 2短图片，3短视频，11用户买家秀
    if (item.feed_type === 11) {
      url = status ? requestApi.cancelLikeBuyerShow : requestApi.setLikeBuyerShow
      params.comment_id = feedId
    } else {
      url = status ? requestApi.cancelLikeCommunityContent : requestApi.likeCommunityContent
      params.feed_id = feedId
    }

    app.request({
      url,
      data: params,
    }, () => {
      // 更新 点赞状态、点赞数
      item.liked_amount = status ? item.liked_amount - 1 : item.liked_amount + 1

      this.setData({
        [`showList[${columnIndex}][${itemIndex}].new_liked_amount`]: this.formatLikeCount(item.liked_amount),
        [`showList[${columnIndex}][${itemIndex}].is_favorite`]: !item.is_favorite,
      })
    }, (error) => {
      wx.showModal({
        title: '提示',
        content: error,
        showCancel: false,     
      })
    }, () => {
      this.data.praiseRequestFlag = false
    })
  },

  // show 瀑布流：两列
  // rpx换算px (屏幕宽度/750)
  // iPhone6 1rpx = 0.5px
  // 依赖卡片布局样式！！！
  initWaterfallList(list) {
    list.forEach((item, index) => {
      // 图片等格式化
      item.avatar_full = formatImage.cdnImage(item.avatar, formatImage.THUMBNAIL_M)
      item.cover_image.path_full = formatImage.cdnImage(item.cover_image.path, formatImage.THUMBNAIL_M)
      item.is_favorite = !!item.is_favorite
      item.new_liked_amount = this.formatLikeCount(item.liked_amount)
  
      // 46rpx 为卡片padding边距
      // 134rpx 为卡片内容文本区域：最小高度（一行文本）
      // 174rpx 为卡片内容文本区域：最大高度（两行文本）
      // 25 估算的一行文本长度
      const ratio = this.data.winWidth / 750
      const cardWidth = (this.data.winWidth - ratio * 46) / 2
      const scale = cardWidth / item.cover_image.width
      const contentHeight = item.title
        ? (item.title.replace(/[^\x00-\xff]/g, '**').length < 25 ? 134 : 174) * ratio
        : 0
      const height = scale * item.cover_image.height + Math.round(contentHeight)

      // 第一行的两个盒子
      if (this.data.page === 1 && index < this.data.colCount) {
        this.data.showList.push([item])
        this.data.heightArr.push(height)
      } else {
        // 选出高度较矮的一列的索引
        const minHeight = Math.min.apply(null, this.data.heightArr)
        const minHeightIndex = this.data.heightArr.indexOf(minHeight)

        this.data.showList[minHeightIndex].push(item)
        this.data.heightArr[minHeightIndex] += height
      }
    })
  },

  // 加载更多
  scrollToLower() {
    if (this.data.noMore) return

    this.data.page = this.data.page + 1
    this.getSpuContentList()
  },
})
